// pages/category/category.js
const app = getApp();
const util = require('../../../utils/util.js')

import { treelist } from '../../../api/product'
import { add, getCart, update, clear, del, build } from '../../../api/cart'
import { find, list as shopList } from '../../../api/shop'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    windowHeight: app.globalData.windowHeight,
    safeAreaBottom: 22,
    statusBarHeight: app.globalData.statusBarHeight,
    mchName: app.globalData.mchName,
    mchId: null,
    emptyImage: 'http://cdnx.rzico.com/images/pcLogo.png',
    bgEmptyImage: 'http://cdnx.rzico.com/images/std_bg.jpg',
    eInfo: "", //暂存购物车动画的e数据
    active: 0,
    amount: 0,
    buildAmount: 0,
    quantity: 0,
    shopInfo: {},
    couponList: [],
    promotions: [],
    notice: '',
    skeletonShow: true,
    classifyData: [],
    productData: [],
    topHeight: null,
    topTitleList: [],
    reScrollTop: 0,
    scrollTop: 0,
    heardHeight: 0,
    cartList: [],
    frameType: 0,
    timer: null,
    startY: 0,
    expand: false,
    shopId: null,
    paused: false,
    shippingConfig: {},
    tabbarHeight: app.globalData.tabbarHeight,
    currNode: null,
    scrollFlag: true, //点击左侧分类栏时禁用滑动获取分类事件
    nextFlag: true, //滑动分类时获取了下一个分类禁用滑动获取分类事件
    activeFlag: true,
    productLoading: false,
    pullDownRefresh: false,
    checkCardTimer: null
  },

  watch: function (path, callback) {
    let value = this.data[path];
    const that = this;
    Object.defineProperty(this.data, path, {
      configurable: true,
      enumerable: true,
      get: () => { return value; },
      set: (newVal) => {
        if (newVal !== value) {
          const oldVal = value;
          value = newVal;
          callback(newVal, oldVal);
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let navHeight;
    const that = this
    const sysinfo = wx.getSystemInfoSync(), menuButton = wx.getMenuButtonBoundingClientRect(),
      rpxR = 750 / sysinfo.windowWidth,
      statusHeight = sysinfo.statusBarHeight * rpxR,
      isiOS = sysinfo.system.indexOf('iOS') > -1;

    that.data.windowWidth = sysinfo.windowWidth * rpxR;
    that.data.windowHeight = sysinfo.windowHeight * rpxR;
    that.data.safeAreaBottom = (sysinfo.screenHeight - sysinfo.safeArea.bottom) * rpxR;
    that.data.rpxR = rpxR;
    that.data.menuBtnTop = menuButton["top"] * app.globalData.rpxR;

    if (!isiOS) navHeight = 46 * rpxR;
    else navHeight = 42 * rpxR;

    this.setData({
      menuBtnTop: that.data.menuBtnTop,
      safeAreaBottom: that.data.safeAreaBottom,
      windowWidth: that.data.windowWidth,
      windowHeight: that.data.windowHeight,
      status: statusHeight,
      navHeight: navHeight,
      mchId: app.globalData.mchId
    })

    this.watch('active', (newVal, oldVal) => {
      if (newVal != oldVal) that.data.nextFlag = true;
    })

    this.watch('reScrollTop', (newVal, oldVal) => {
      wx.pageScrollTo({ scrollTop: newVal, duration: 0 })
    })
    that.getLoadProduct()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this
    that.getShopInfo((res) => that.setData({ shopInfo: res, mchName: app.globalData.mchName, mchId: app.globalData.mchId }))

    this.watch('mchId', (newVal, oldVal) => {
      if (newVal != oldVal) {
        that.setData({ productData: [], topTitleList: [], classifyData: [] })
        that.getLoadProduct()
      }
    })

    this.getShoppingCart((res) => {
      that.data.cartList = res
      if (res.itemVoList.length > 0) {
        let _amount = 0, _quantity = 0
        that.data.cartList.itemVoList.map((el) => {
          _amount += (el.quantity * el.price) * 1;
          _quantity += parseInt(el.quantity);
        })
        that.setData({
          cartList: that.data.cartList,
          amount: _amount,
          quantity: _quantity
        })
        that.buildAmount(data => that.setData({ buildAmount: data.amount }))
      }
    });
  },

  getLoadProduct(callback) {
    const that = this
    that.getProductrequest((data) => {
      that.data.skeletonShow = false;
      that.data.classifyData = data;
      that.data.classifyData.map((el, index) => {
        if (!util.isNull(el.childrens)) {
          el.index = index
          that.data.productData[index] = el
        }

        if (index == 0) that.data.productData[0] = el;
      })
      that.setData({
        classifyData: that.data.classifyData,
        productData: that.data.productData,
        skeletonShow: that.data.skeletonShow,
      })
      that.getNodesInfo((data) => {
        that.data.reScrollTop = data[0].top
        let { active, classifyData, windowHeight, status, navHeight, rpxR } = that.data
        const LoadNextHeight = (windowHeight - status - navHeight) / rpxR //因为节点计算返回的是 px 所以需要将 rpx 转 px
        const isLoadNext = (data[0].height - LoadNextHeight) < (data[0].height / 2) || that.data.productData[0].childrens == 0 //判断元素高度减去视图高度后小于自身的一半

        if (isLoadNext && util.isNull(classifyData[active + 1].childrens) && active < classifyData.length - 1) {
          that.data.currNode = classifyData[active + 1].id
          that.getNextProduct(() => that.getNodesInfo())
        }

        if (callback) callback();
      });
    })
  },

  // 获取滚动的距离
  getNodesInfo(callback) {
    //console.log('getNodesInfo-启动')
    const that = this;
    const selectorQuery = wx.createSelectorQuery();

    selectorQuery.selectAll('.rigtht_content_title').boundingClientRect()
      .selectAll('.menu_rigtht_content').boundingClientRect()
      .exec((nodes) => {
        // 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
        let topTitleList = []
        let topTitleObj = {}
        nodes.map(el => {
          if (!el.length) {
            setTimeout(() => { that.getNodesInfo() }, 100);
            return;
          }
        })
        // 生成之后开始添加进去数组
        let linkTop = 0
        nodes[0].map((el, oneIndex) => {
          // 这里减去rects[0].top，是因为第一项顶部不是贴到导航栏=>每一个商品距离顶部的高度，如果此页面顶部没有其他的view那就不用减去rects[0].top，自己视情况而定。
          // let top = el.top - nodes[0][0].top;
          let index = nodes[1].findIndex(find => find.dataset.id === el.dataset.id);
          let twoIndex = that.data.productData.findIndex(find => find.id === el.dataset.id);
          let height = nodes[1][index].height;

          if (oneIndex > 0) linkTop += nodes[1][index - 1].height;

          topTitleObj = { top: linkTop, height: height, id: el.dataset.id, index: el.dataset.index }
          topTitleList.push(topTitleObj)

          that.data.productData[twoIndex].topTitleList = topTitleObj
        })
        that.data.topTitleList = topTitleList
        if (callback) callback(topTitleList);
      })
  },

  // 监听右侧内容滚动事件
  onPageScroll(e) {
    const that = this
    let scrollTop = e.scrollTop + 40;
    if (this.data.scrollFlag) {
      const { active, classifyData, nextFlag, productData } = this.data
      let nextIndex = active + 1;
      // 遍历分类，计算每个分类的位置
      productData.map((item, index) => {
        let category = item.topTitleList
        if (!util.isNull(category.top)) {
          const categoryTop = category.top;
          const categoryBottom = category.height + category.top;
          if (scrollTop >= (categoryBottom / 2) && (active < classifyData.length - 1 && util.isNull(classifyData[active + 1].childrens)) && nextFlag && active < classifyData.length - 1) {
            that.data.nextFlag = false;
            that.data.currNode = classifyData[nextIndex].id
            that.getNextProduct(() => setTimeout(() => { that.getNodesInfo() }, 200))
          }
          if (scrollTop >= categoryTop && scrollTop < categoryBottom) {
            // 如果当前分类与新计算出来的分类不同，则更新
            if (item.index !== active) {
              this.data.leftFlag = false
              this.setData({
                active: item.index,
                leftScrollTop: 112 * (item.index - this.data.leftViewNum + 2)
              });
              // if (that.data.active > 0 && util.isNull(classifyData[that.data.active - 1].childrens)) {
              //   that.data.currNode = classifyData[that.data.active - 1].id
              //   that.getPrevProduct(() => {
              //     setTimeout(() => { that.getNodesInfo() }, 200)
              //   })
              // }
            }
          }
        }
      });
    }
  },

  //分类的点击事件
  selectMenu(e) {
    const { index, id } = e.currentTarget.dataset;
    const that = this;
    if (index === this.data.active) {
      return;
    }
    this.data.currNode = id
    this.data.classifyData.map(el => {
      el.childrens = []
      el.topTitleList = {}
    });

    that.setData({
      productData: [],
      topTitleList: [],
      classifyData: this.data.classifyData,
      nextFlag: false,
      scrollFlag: false,
      productLoading: true
    })

    that.getProductrequest((data) => {
      that.data.classifyData[index] = data[0];
      that.data.classifyData.map((el, el_index) => {
        if (!util.isNull(el.childrens)) {
          el.index = index
          that.data.productData.push(el)
        }
      })
      that.setData({
        active: index,
        classifyData: that.data.classifyData,
        productData: that.data.productData,
        productLoading: false
      })
      setTimeout(() => {
        that.getNodesInfo((data) => {
          // let find_index = data.findIndex(find => find.index === index)
          let { topTitleList, classifyData, windowHeight, status, navHeight } = that.data
          that.data.reScrollTop = 0
          that.data.scrollFlag = true
          const isLoadNext = topTitleList[0].height <= windowHeight - (status + navHeight + 120) //判断当前元素高度是否和视图高度的差值
          if (isLoadNext && util.isNull(classifyData[index + 1].childrens) && index < classifyData.length - 1) {
            that.data.currNode = classifyData[index + 1].id
            that.getNextProduct(() => setTimeout(() => { that.getNodesInfo() }, 200))
          }
        });
      }, 200)

      // if (index > 0 && util.isNull(that.data.classifyData[index - 1].childrens)) {
      //   that.data.currNode = that.data.classifyData[index - 1].id
      //   that.getPrevProduct(() => {
      //     setTimeout(() => {
      //       that.getNodesInfo(data => {
      //         that.data.reScrollTop = data[1].top
      //         this.data.scrollFlag = true
      //       })
      //     }, 200)
      //   })
      // } else {
      //   setTimeout(() => {
      //     that.getNodesInfo((data) => {
      //       // let find_index = data.findIndex(find => find.index === index)
      //       that.data.reScrollTop = 0
      //       this.data.scrollFlag = true
      //     });
      //   }, 200)
      // }
    })
  },

  getShopInfo(callback) {
    const that = this
    shopList({ keyword: app.globalData.mchName, pageNum: 1, pageSize: 1 }).then(res => {
      if (callback) callback(res.data[0]);
    })
  },

  detailsClick(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({ url: '/pages/goods/product/details?id=' + id })
  },

  getShoppingCart(callback) {
    const that = this
    getCart({ mchId: app.globalData.mchId }).then(res => { if (callback) callback(res.data.cart) })
  },

  backClick() {
    wx.navigateBack({
      delta: 1,
      fail: res => wx.switchTab({ url: '/pages/index/index', })
    })
  },

  //跳转搜索页
  categorySearch() {
    wx.navigateTo({ url: '/pages/goods/search/index' })
  },

  /**
   * 初始化获取商品列表信息 
   * @param {Function} callback
   * @return {Object} 返回商品对象
   */
  getProductrequest(callback) {
    const that = this;
    let params = {
      version: '2.0',
      pageNum: that.data.pageNum,
      pageSize: that.data.pageSize,
      mchId: app.globalData.mchId,
    }
    if (!util.isNull(that.data.currNode)) params.currNode = that.data.currNode;

    treelist(params).then(res => {
      if (res.type == 'success') { if (callback) callback(res.data) }
    }).catch(error => console.error(error))
  },

  /**
   * 获取上一个分类商品列表信息 
   * @param {Function} callback
   */
  getPrevProduct(callback) {
    this.getProductrequest((data) => {
      const { active, classifyData } = this.data;
      const that = this
      data.map(el => {
        if (el.id == classifyData[active - 1].id) {
          el.index = active - 1

          that.data.classifyData[active - 1] = data[0];
          that.data.productData = this.uniqueByKey([...data, ...that.data.productData], 'id')
          that.setData({
            classifyData: that.data.classifyData,
            productData: that.data.productData,
          })
        }
      })
      if (callback) callback()
    })
  },

  /**
 * 获取下一个分类商品列表信息 
 * @param {Function} callback
 */
  getNextProduct(callback) {
    this.getProductrequest((data) => {
      const { active, classifyData } = this.data, that = this
      data.map(el => {
        if (el.id == classifyData[active + 1].id) {
          that.data.classifyData[active + 1] = data[0];
          el.index = active + 1
          that.data.productData = this.uniqueByKey([...that.data.productData, ...data], 'id')
          that.setData({
            classifyData: that.data.classifyData,
            productData: that.data.productData,
          })
        }
      })
      if (callback) callback()
    })
  },

  uniqueByKey(array, key) {
    return array.filter((item, index) => array.findIndex(other => JSON.stringify(other[key]) === JSON.stringify(item[key])) === index);
  },

  addProductToCart(e) {
    if (util.isNull(app.globalData.token)) {
      wx.navigateTo({ url: '/pages/login/index' })
      return
    }
    const that = this
    const { productinfo } = e.currentTarget.dataset;
    let productId = productinfo.id;

    this.data.eInfo = e;

    if (e.currentTarget.dataset.productinfo.sku > 1) this.selectComponent('#bottomFrame').showFrame(productId, "addCart");
    else {
      //发送添加购物车的请求
      let data = {};
      data.productId = productId;
      data.promotionId = "";
      data.quantity = e.currentTarget.dataset.productinfo.minLimit;
      data.uuid = app.globalData.uuid;

      add(data).then(res => {
        if (res.type == 'success') {
          this.setData({ buildAmount: '优惠计算中' })
          wx.showToast({
            title: '成功加入购物车',
            icon: 'none'
          })
          this.selectComponent('#addCart').getCartCount();
          this.selectedInfo();
        }
      }).catch(error => console.log(error))
    }
  },

  //属性选择弹窗完成后数据回传函数
  selectedInfo(data) {
    const that = this
    this.selectComponent('#addCart').touchOnGoods(this.data.eInfo);
    setTimeout(() => {
      this.getShoppingCart((res) => {
        that.data.cartList = res
        that.buildAmount(data => that.setData({ buildAmount: data.amount }))
      });
    }, 500)
  },

  hideFrame() {
    const that = this
    that.buildAmount(data => that.setData({ buildAmount: data.amount }))
  },

  frameChange(e) {
    const { type } = e.currentTarget.dataset;
    this.data.cartShow = !this.data.cartShow;
    this.data.frameType = type ? type : 0;
    this.setData({
      cartList: this.data.cartList,
      cartShow: this.data.cartShow,
      frameType: this.data.frameType
    })
  },
  checkCardChange(e) {
    console.log(e);
    const that = this
    clearTimeout(this.data.checkCardTimer)

    const { index } = e.currentTarget.dataset
    this.data.cartList.itemVoList[index].chk = !this.data.cartList.itemVoList[index].chk
    const allFalse = this.data.cartList.itemVoList.every(e => e.chk === false)

    if (allFalse) {
      this.data.cartList.itemVoList[index].chk = !this.data.cartList.itemVoList[index].chk
      wx.showToast({
        title: '至少要选择一个哦',
        icon: "none"
      })
      return
    }

    this.data.checkCardTimer = setTimeout(() => {
      if (that.data.cartList.itemVoList.length > 0) {
        let dataList = []
        let amount = 0
        let quantity = 0
        that.data.cartList.itemVoList.map((el) => {
          let data = {};
          data.price = el.price;
          data.productId = el.productId;
          data.quantity = el.quantity;
          data.chk = el.chk;
          data.id = el.id;
          dataList.push(data);
          amount += (el.quantity * el.price) * 1;
          quantity += parseInt(el.quantity);
        })
        that.setData({
          cartList: this.data.cartList,
          amount: amount.toFixed(2),
          quantity: quantity,
          buildAmount: '优惠计算中'
        })
        that.cartUpdate(dataList, () => {
          that.buildAmount(res => that.setData({ buildAmount: res.amount }))
        })
      }
    }, 500)
  },
  calculate(e) {
    const that = this,
      { index, type } = e.currentTarget.dataset;
    let item = this.data.cartList.itemVoList[index];

    if (type == 'add') {
      if (item.maxLimit != 0 && item.quantity > item.maxLimit) {
        wx.showToast({
          title: '商品数量达到限购量了呦！',
          icon: 'none',
        })
        this.data.cartList.itemVoList[index].quantity = item.maxLimit;
        return;
      }
      this.data.cartList.itemVoList[index].quantity++;
      that.calculateCart()
    } else {
      if (item.quantity == 1 || item.quantity <= item.minLimit) {
        wx.showModal({
          title: '提示',
          content: '已达到最小数量，确认删除吗？',
          complete: (res) => {
            if (res.cancel) { return; }
            if (res.confirm) {
              that.handleDelete(e, () => {
                that.data.cartList.itemVoList.splice(index, 1);
                wx.showToast({
                  title: '删除成功',
                  icon: 'none'
                })
                let _amount = 0, _quantity = 0
                that.data.cartList.itemVoList.map((el) => {
                  _amount += (el.quantity * el.price) * 1;
                  _quantity += parseInt(el.quantity);
                })
                that.setData({
                  cartList: that.data.cartList,
                  amount: _amount.toFixed(2),
                  quantity: _quantity,
                  buildAmount: that.data.buildAmount,
                })
                that.calculateCart()
              });
            }
          }
        })
      } else {
        that.data.cartList.itemVoList[index].quantity--;
        that.calculateCart()
      }
    }
  },

  calculateCart() {
    const that = this
    let dataList = [], amount = 0, quantity = 0

    if (that.data.cartList.itemVoList.length > 0) {
      that.data.cartList.itemVoList.map((el) => {
        let data = {};
        data.price = el.price;
        data.productId = el.productId;
        data.quantity = el.quantity;
        data.chk = true;
        data.id = el.id;
        dataList.push(data);
        amount += (el.quantity * el.price) * 1;
        quantity += parseInt(el.quantity);
      })
      that.setData({
        cartList: this.data.cartList,
        amount: amount.toFixed(2),
        quantity: quantity,
        buildAmount: '优惠计算中'
      })
      clearTimeout(that.data.timer)
      that.data.timer = setTimeout(() => {
        that.cartUpdate(dataList, () => {
          that.buildAmount(res => that.setData({ buildAmount: res.amount }))
        })
      }, 700)
    } else {
      that.setData({ buildAmount: 0 })
    }
  },

  buildAmount(callback) {
    build({ shopId: this.data.shopId }).then(res => {
      if (res.type == 'success') {
        if (callback) callback(res.data);
      }
    })
  },

  //调用购物车的数量更新接口
  cartUpdate(data, callback) {
    const that = this
    update(data).then(res => {
      if (res.type == 'success') { if (callback) callback(); }
    }).catch(error => {
      wx.showToast({
        title: error.content,
        icon: 'none',
      })
    })
  },

  cartClear() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '确认清空购物车吗？',
      complete: (res) => {
        if (res.cancel) { return false; }
        if (res.confirm) {
          clear({ uuId: util.getUUID() }).then(res => {
            this.data.cartList.itemVoList = [];
            this.setData({
              cartList: this.data.cartList,
              amount: 0,
              quantity: 0,
              buildAmount: 0
            })
          })
        }
      }
    })
  },

  //跳转订单确认页面
  productSumbit: function (e) {
    const that = this
    let dataList = [], _amount = 0, _quantity = 0

    this.getShoppingCart((data) => {
      this.data.cartList.itemVoList.map((el) => {
        let data = {};
        data.price = el.price;
        data.productId = el.productId;
        data.quantity = el.quantity;
        data.chk = true;
        data.cartId = this.data.cartList.id;
        data.id = el.id;
        dataList.push(data);
        _amount += (el.quantity * el.price) * 1;
        _quantity += parseInt(el.quantity);
      })
      this.setData({
        cartList: this.data.cartList,
        amount: _amount.toFixed(2),
        quantity: _quantity
      })
      this.cartUpdate(dataList, () => {
        wx.navigateTo({ url: `/pages/goods/submit/index` })
      })
    })
  },

  //下拉刷新
  onPullDownRefresh() {
    const that = this
    const { classifyData, active } = this.data
    if (active > 0) {
      if (util.isNull(classifyData[active - 1].childrens)) {
        this.setData({ pullDownRefresh: true })
        this.data.currNode = classifyData[active - 1].id
        this.getPrevProduct(() => {
          setTimeout(() => {
            that.getNodesInfo(data => {
              that.data.reScrollTop = 0
              that.data.scrollFlag = true
              that.setData({ pullDownRefresh: false, active: active - 1 })
              wx.stopPullDownRefresh()
            })
          }, 200)
        });
      }
    }
    if (active == 0) {
      that.data.currNode = ''
      this.setData({
        productLoading: true,
        classifyData: [],
        productData: [],
      })
      wx.stopPullDownRefresh()
      this.getLoadProduct(() => {
        that.setData({ productLoading: false })
      })
    }
  },

  handleDelete(e, callback) {
    const { id, index } = e.currentTarget.dataset;
    del(id).then(res => { if (callback) callback(res) })
  },

  expandHeard() {
    this.data.expand = !this.data.expand
    this.setData({ expand: this.data.expand })
  },

  heardTouchstart(e) {
    this.data.startY = e.changedTouches[0].pageY
  },

  heardTouchmove(e) {
    if (this.data.startY - e.changedTouches[0].pageY > 10) this.data.expand = false;
    this.setData({ expand: this.data.expand })
  },
  toSearch() {
    wx.navigateTo({
      url: '/pages/goods/search/index'
    })
  },
})
